package cn.szzsi.model;

import cn.szzsi.common.util.CommonUtil;
import cn.szzsi.model.base.BaseMember;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;

/**
 * 实体类 - 会员
 */
public class Member extends BaseMember<Member> {

    private static final long serialVersionUID = 1312507976941245078L;

    public static final String LOGOUT_URL = "logoutUrl";// 退出登陆时跳转url
    public static final String LOGIN_USER_INFO = "userInfo";// 保存登录会员信息
    public static final String LOGIN_MEMBER_ID_SESSION_NAME = "loginMemberId";// 保存登录会员ID的Session名称
    public static final String LOGIN_CUSTOMER_ID_SESSION_NAME = "logincCustomerId";// 保存登录用户ID的Session名称
    public static final String LOGIN_MEMBER_USERNAME_COOKIE_NAME = "loginMemberUsername";// 保存登录会员用户名的Cookie名称
    public static final String LOGIN_TYPE_COOKIE_NAME = "loginMemberType";// 保存登录类型Cookie名称(business:商户,customer:用户)
    public static final String LOGIN_REDIRECTION_URL_SESSION_NAME = "redirectionUrl";// 保存登录来源URL的Session名称
    public static final String PASSWORD_RECOVER_KEY_SEPARATOR = "_";// 密码找回Key分隔符
    public static final int PASSWORD_RECOVER_KEY_PERIOD = 30;// 密码找回Key有效时间（单位：分钟）

    private Map<String, String> memberAttributeMapStore = new HashMap<String, String>(); // 会员注册项储存

    public static final Member dao = new Member().dao();

    public boolean containEmail(String email) {
        return dao.findFirst("select email from sys_member where email=? limit 1", email) != null;
    }

    public boolean containUsername(String username) {
        return dao.findFirst("select username from sys_member where username=? limit 1", username) != null;
    }

    public Member updateUsername(String username,String shopId,String id){
        return dao.findFirst("select username from sys_member where username=? and shopId=? and id!=?", username,shopId,id);
    }

    /**
     * 获得某人的直谏会员
     *
     * @param member
     * @return
     */
    public List<Member> getFirstRecommendByMember(Member member) {
        return dao.find("select * from sys_member where pid = ? order by createDate desc", member.getStr("id"));
    }

    /**
     * 获得某人的所有会员数
     *
     * @param member
     * @return
     */
    public long getRecommendNum(Member member) {
        System.out.println("select count(*) from sys_member where pids like '%" + member.getStr("id") + "%' order by createDate desc");
        return Db.queryColumn("select count(*) from sys_member where pids like '%" + member.getStr("id") + "%' order by createDate desc");
    }

    /**
     * 获得某人次一级的直谏会员
     *
     * @param member
     * @param level  级别,一般是2、3级
     * @return
     */
    public List<Member> getFirstRecommendByMember(Member member, int level) {
        List<Member> list = dao.find("select * from sys_member where pids like ?", "%" + member.getStr("id") + "%");
        List<Member> members = new ArrayList<Member>();
        String tmp = "";
        try {
            if (level == 2) {
                for (Member m : list) {
                    tmp = org.apache.commons.lang3.StringUtils.substring(m.getStr("pids"), org.apache.commons.lang3.StringUtils.indexOf(m.getStr("pids"), member.getStr("id")));
                    if (org.apache.commons.lang3.StringUtils.countMatches(tmp, ",") == 1) {
                        members.add(m);
                    }
                }
            } else if (level == 3) {
                for (Member m : list) {
                    tmp = org.apache.commons.lang3.StringUtils.substring(m.getStr("pids"), org.apache.commons.lang3.StringUtils.indexOf(m.getStr("pids"), member.getStr("id")));
                    if (org.apache.commons.lang3.StringUtils.countMatches(tmp, ",") == 2) {
                        members.add(m);
                    }
                }
            }
        } catch (Exception e) {

        }
        return members;
    }


    /**
     * 根据用户名获取会员对象，若会员不存在，则返回null（不区分大小写）
     * 验证平台用户.......
     */
    public Member getMemberByUsername(String username) {
        return dao.findFirst("select * from sys_member where username = ? and shopId ='-1' ", username);
    }


    /**
     * 根据用户名获取会员对象，若会员不存在，则返回null（不区分大小写）
     */
    public Member getBusinessByUsername(String username) {//验证商户
        return dao.findFirst("select * from sys_member where username = ? and shopId ='0' ", username);
    }

    /**
     * 根据用户名,手机号,邮箱,获取会员对象，若会员不存在，则返回null（不区分大小写）
     * @param username
     * @return
     */
    public Member getBusinessByAll(String username) {//验证商户
        Member member=dao.findFirst("select * from sys_member where username = ? and shopId ='0' ", username);
        CompanyInfo co=CompanyInfo.dao.findFirst("select * from sys_company_info where email=? or phone=?",username,username);
        if(member!=null){
             return member;
        }else if(co!=null){
            Member superMember=dao.findById(co.getShopId());
            return superMember;
        }else{
            return null;
        }

    }



    /**
     * 根据用户名获取会员对象，若会员不存在，则返回null（不区分大小写）
     * 验证商户用户
     */
    public Member getCustomerByUsername(String username) {
        return dao.findFirst("select * from sys_member where username = ? and shopId !='-1' and shopId!='0' ", username);
    }

    /**
     * 根据用户名获取会员对象，若会员不存在，则返回null（不区分大小写）
     */
    public Member getCustomerByUsernameAndShopId(String username, String shopId) {//验证商户的用户
        return dao.findFirst("select * from sys_member where username = ? and shopId=? ", username, shopId);
    }

    /**
     * 根据用户名判断此用户是否存在（不区分大小写）
     */
    public boolean isExistByUsername(String username) {
        String sqlMember = "select * from sys_member where lower(username) = lower(?) and shopId='-1'";
        String sqlAdmin = "select * from sys_admin where lower(username) = lower(?)";
        Member member = dao.findFirst(sqlMember, username);
        Admin admin = Admin.dao.findFirst(sqlAdmin, username);
        if (member != null || admin != null) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 根据用户名判断此用户是否存在（不区分大小写）
     */
    public boolean isExistByUsername(String username, String shopId) {
        String sqlMember = "select * from sys_member where lower(username) = lower(?) and shopId=?";
        String sqlAdmin = "select * from sys_admin where lower(username) = lower(?)";
        Member member = dao.findFirst(sqlMember, username, shopId);
        Admin admin = Admin.dao.findFirst(sqlAdmin, username);
        if (member != null || admin != null) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据用户名判断此用户是否存在（不区分大小写）
     */
    public boolean isExistByCustomerUsername(String username, String shopId) {
        String sqlMember = "select * from sys_member where lower(username) = lower(?) and shopId=?";
        String sqlAdmin = "select * from sys_admin where lower(username) = lower(?)";
        Member member = dao.findFirst(sqlMember, username, shopId);
        Admin admin = Admin.dao.findFirst(sqlAdmin, username);
        if (member != null || admin != null) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 根据用户名、密码验证会员
     *
     * @param username 用户名
     * @param password 密码
     * @return 验证是否通过
     */
    public boolean verifyCustomer(String username, String password, String shopId) {
        Member member = getCustomerByUsernameAndShopId(username, shopId);
        if (member != null && member.getStr("password").equals(DigestUtils.md5Hex(password))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据用户名、密码验证会员
     *
     * @param member 商户实体
     * @param password 密码
     * @return 验证是否通过
     */
    public boolean verifyMember(Member member, String password) {
        if (member != null && DigestUtils.md5Hex(password).equals(member.getStr("password"))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据用户名、密码验证会员
     *
     * @param username 用户名
     * @param password 密码
     * @return 验证平台用户是否通过
     */
    public boolean verifyCustomerMember(String username, String password) {
        Member member = getMemberByUsername(username);
        if (member != null && member.getStr("password").equals(DigestUtils.md5Hex(password))) {
            return true;
        } else {
            return false;
        }
    }




    /**
     * 生成密码找回Key
     *
     * @return 密码找回Key
     */
    public String buildPasswordRecoverKey() {
        return System.currentTimeMillis() + Member.PASSWORD_RECOVER_KEY_SEPARATOR + CommonUtil.getUUID() + DigestUtils.md5Hex(CommonUtil.getRandomString(10));
    }

    /**
     * 根据密码找回Key获取生成日期
     *
     * @return 生成日期
     */
    public Date getPasswordRecoverKeyBuildDate(String passwordRecoverKey) {
        long time = Long.valueOf(StringUtils.substringBefore(passwordRecoverKey, Member.PASSWORD_RECOVER_KEY_SEPARATOR));
        return new Date(time);
    }

    /**
     * 获取所有实体对象总数.
     *
     * @return 实体对象总数
     */
    public Long getTotalCount() {
        String sql = "select count(*) from sys_member ";
        return Db.queryLong(sql);
    }

    // 等级
    public MemberRank getMemberRank() {
        String sql = "select * from sys_member_rank where id = ? order by createDate desc";
        return MemberRank.dao.findFirst(sql, getStr("memberRank_id"));
    }



    public Member isExistByOpenid(String openid) {
        return Member.dao.findFirst("select * from sys_member where openid=?", openid);
    }

    public Member getByOpenid(String openid) {
        return Member.dao.findFirst("select * from sys_member where openid=?", openid);
    }

    /**
     * 根据手机号查询该商户是都注册
     * @param phone
     * @return
     */
    public Member getByPhone(String phone) {
        return Member.dao.findFirst("select * from sys_member where phone=?", phone);
    }

    //保存微信拉取的用户信息
    public static final Member saveMemberInfo(String pid, String pids, String openid, String username, String sex, String country, String province, String city, String headimgurl, String privilege, String unionid, String shopId, String registerIp, String code) {
        Member member = new Member();
        member.set("pid", pid);
        member.set("pids", pids);
        member.set("openid", openid);
        if (StrKit.isBlank(sex)) {
            sex = "0";
        }
        member.set("sex", sex);
        member.set("country", country);
        member.set("province", province);
        member.set("city", city);
        member.set("headimgurl", headimgurl);
        member.set("privilege", privilege);
        member.set("unionid", unionid);
        member.set("id", CommonUtil.getUUID());
        member.set("username", username);
        member.set("password", openid);
        member.set("shopId", shopId);
        member.set("safeQuestion", null);
        member.set("safeAnswer", null);
        member.set("memberRank_id", MemberRank.dao.getDefaultMemberRank(shopId).getStr("id"));
        member.set("point", 0);
        member.set("deposit", new BigDecimal("0"));
        member.set("isAccountEnabled", true);
        member.set("isAccountLocked", false);
        member.set("loginFailureCount", 0);
        member.set("passwordRecoverKey", null);
        member.set("lockedDate", null);
        member.set("loginDate", new Date());
        if (StrKit.isBlank(registerIp)) {
            registerIp = "127.0.0.1";
        }
        member.set("registerIp", registerIp);
        member.set("loginIp", registerIp);
        member.set("createDate", new Date());
        member.set("code", code);
        member.save();
        return member;
    }


    /**
     * 新增商户
     * @param phone
     * @param username
     * @param password
     * @param userimgurl
     * @return
     */
    public static final Member saveBusiness(String phone,String username,String password,String userimgurl){
        Member member=new Member();
        member.set("id", CommonUtil.getUUID());
        member.set("username", username);
        member.set("password", DigestUtils.md5Hex(password));
        member.set("userimgurl", userimgurl);
        member.set("shopId", "0");
        member.set("createDate", new Date());
        member.set("roleId", "super");
        member.set("b_shoprank", "super");
        member.set("isAccountEnabled", 1);
        member.set("isAccountLocked", 0);
        member.set("loginFailureCount", 0);
        member.set("phone", phone);
        member.set("registerIp", "");
        member.setType(1);//商户
        member.save();
        return member;
    }

    public Role getByRoleId() {
        return Role.dao.findById(getStr("roleId"));
    }

    public void init() {
        String roleId = this.getStr("roleId");
        Role br = Role.dao.findById(roleId);
        this.put("roleName", br == null ? "" : br.getStr("name"));
    }






}
